#coding= utf-8
import asyncio
import aiohttp



class AsnycSpider(object):
    def __init__(self):
        self.result = []
    
    async def postinfo(self,url,_header,_data):
        async with aiohttp.ClientSession() as session:
            async with session.post(url, headers=_header,data=_data,timeout=5) as response:
                if response.status == 200:
                    html = await response.text()
                    self.result.append(html)

    async def getinfo(self,url,_header):
        async with aiohttp.ClientSession() as session:
            async with session.get(url, headers=_header,timeout=5) as response:
                if response.status == 200:
                    html = await response.text()
                    self.result.append(html)

    def aioget(self,url_list,_header):
        tasks = [asyncio.ensure_future(self.getinfo(url,_header)) for url in url_list]
        loop = asyncio.get_event_loop()
        loop.run_until_complete(asyncio.wait(tasks))
        #loop.close()

    def aiopost(self,url_list,_header,_data):
        tasks = [self.postinfo(url,_header,_data) for url in url_list]
        loop =  asyncio.new_event_loop()
        asyncio.set_event_loop(loop)
        #loop = asyncio.get_event_loop()
        print('1')
        tasks = asyncio.gather(*tasks)
        loop.run_until_complete(tasks)
        print('22')
        #loop.close()



if __name__ == '__main__':
    urls = [
    'https://www.baidu.com/',
    'https://xiapi.xiapibuy.com/api/v2/search_items/?by=relevancy&fe_categoryids=62&limit=50&newest=0&order=desc&page_type=search&version=2',
    'https://cn.bing.com/',
]
    HTTP_HEADER = {
        "Accept": "application/json",
        "Accept-Encoding": "gzip, deflate, br",
        "Accept-Language": "zh-CN,zh;q=0.9",
        "Cache-Control": "no-cache",
        "Connection": "keep-alive",
        "Pragma": "no-cache",
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36",
        
        }
    datas = {
        "key":"sss"
    }
    a=AsnycSpider()
    a.aiopost(urls,HTTP_HEADER,datas)
    print(a.result)
    print(len(a.result))
